package com.ardiudiu.studio;

import java.util.HashMap;
import java.util.Map;

import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.text.ClipboardManager;
import android.util.Log;

import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;
import com.phonegap.api.Plugin;

public class DiuDiuSharePlugin extends Plugin {

	static final String DO_AUTHORIZE = "do_authorize";
	static final String GET_LINKDATA = "get_linkdata";
	static final String CHECK_AUTHORIZATION = "check_authorization";
	static final String SEND_TOWHATSAPP = "send_whatsapp";

	static final String DROPBOX_CONSUMERKEY = "zhobcgzzriw8yxn";
	static final String DROPBOX_CONSUMERSECRET = "wvnv8frj3jkkya4";

	final static private String ACCOUNT_PREFS_NAME = "DiuDiuSPluginPreference";
	final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
	final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";

	@Override
	public PluginResult execute(String action, JSONArray args, String callbackId) {
		Log.i("ardiudiu studio", "action = [" + action + "] ARRIVED.");
		try {
			if (action.equals(DO_AUTHORIZE)) {
				// test the dropbox authorization
				do_dropbox_authorize();
				boolean result = check_dropbox_authorized();
				return new PluginResult(PluginResult.Status.OK, result);
			} else if (action.equals(CHECK_AUTHORIZATION)) {
				boolean result = check_dropbox_authorized();
				return new PluginResult(PluginResult.Status.OK, result);
			}
			// Parse the arguments
			JSONObject js_arg = args.getJSONObject(0);
			String type = js_arg.has("type") ? js_arg.getString("type") : null;
			Uri uri = js_arg.has("url") ? Uri.parse(js_arg.getString("url")) : null;
			JSONObject js_arg_extra = js_arg.has("extras") ? js_arg.getJSONObject("extras") : null;
			Map<String, String> extrasMap = new HashMap<String, String>();

			// Populate the extras if any exist
			if (js_arg_extra != null) {
				JSONArray extraNames = js_arg_extra.names();
				for (int i = 0; i < extraNames.length(); i++) {
					String key = extraNames.getString(i);
					String value = js_arg_extra.getString(key);
					extrasMap.put(key, value);
				}
			}
			Log.i("ardiudiu studio", action + " >>> start work now !");
			if (action.equals(SEND_TOWHATSAPP)) {
				Intent i = new Intent(action);
				ClipboardManager clipboard = (ClipboardManager) ctx.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
				clipboard.setText(js_arg.getString("content"));
				
				i.setAction(Intent.ACTION_MAIN);
				i.addCategory(Intent.CATEGORY_LAUNCHER);
				i.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Main"));
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				this.ctx.startActivity(i);
			}
			return new PluginResult(PluginResult.Status.OK);
		} catch (Exception e) {
			Log.e("ardiudiu studio", e.getMessage());
			return new PluginResult(PluginResult.Status.ERROR);
		}
	}

	//
	private boolean check_dropbox_authorized() {
		return getAccessToken() == null;
	}

	private void do_dropbox_authorize() {
		AppKeyPair appKeyPair = new AppKeyPair(DROPBOX_CONSUMERKEY, DROPBOX_CONSUMERSECRET);
		AndroidAuthSession session;

		String[] storedAccessToken = getAccessToken();
		if (storedAccessToken == null) {
			// no access token, build a new one, and obtain authorization from
			// user.
			session = new AndroidAuthSession(appKeyPair, AccessType.DROPBOX);
			session.startAuthentication(this.ctx.getContext());
			if (session.authenticationSuccessful()) {
				try {
					session.finishAuthentication();
					AccessTokenPair tokens = session.getAccessTokenPair();
					Editor preferenceEditor = this.ctx.getContext().getSharedPreferences(ACCOUNT_PREFS_NAME, 0).edit();
					preferenceEditor.putString(ACCESS_KEY_NAME, tokens.key);
					preferenceEditor.putString(ACCESS_SECRET_NAME, tokens.secret);
					preferenceEditor.apply();
				} catch (Exception e) {
					Log.e("ardiudiu studio", e.getMessage());
				}
			}
		}
	}

	private String[] getAccessToken() {
		String[] storedAccessToken = null;
		SharedPreferences prefs = this.ctx.getContext().getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		String key = prefs.getString(ACCESS_KEY_NAME, null);
		String secret = prefs.getString(ACCESS_SECRET_NAME, null);
		if (key != null && secret != null) {
			storedAccessToken = new String[2];
			storedAccessToken[0] = key;
			storedAccessToken[1] = secret;
		} else {
		}
		return storedAccessToken;
	}

}
